import mongoose from "mongoose";
import utils from "../utils";
import { isEmail, isPhone } from "../config";
const moment = require("moment");
export interface IEmailCode extends mongoose.Document {
  code: string;
  email: string;
  createTime: string;
  expireTime: string;
}

export const model = {
  code: String,
  email: String,
  createTime: String,
  expireTime: String,
};

export const Schema = new mongoose.Schema(model);

const m: any = mongoose.model<IEmailCode>("EmailCode", Schema);

m.hasExpired = async function(email: string, emailCode: string) {
  const { createTime, expireTime } = await m.findOne({ email, code: emailCode });
  const now = moment().unix();
  if (now > expireTime) {
    return true;
  }
  return false;
};

m.hasEmailCode = async function(emailCode: string, email: string) {
  const res = await m.findOne({ emailCode, email });
  let ret = true;
  if (!res) {
    ret = false;
  }
  return ret;
};

m.delEmailCode = async function(emailCode: string, email: string) {
  const res = await m.deleteOne({ code: emailCode, email });
  if (res.n) {
    return true;
  }
  return false;
};

m.hasEmail = async function(email: string) {
  const res = await m.findOne({ email });
  let ret = true;
  if (!res) {
    ret = false;
  }
  return ret;
};

m.findByEmail = async function(email: string) {
  const res = await m.findOne({ email });
  return res;
};

m.validateEmailCode = async function(emailCode: string, email: string) {
  const res = await m.findOne({ code: emailCode, email });

  if (m.hasEmailCode(emailCode, email)) {
    if (res && res.code == emailCode && !(await m.hasExpired(email, emailCode))) {
      await this.delEmailCode(emailCode, email);
      return true;
    }
    return false;
  }
  return false;
};

export default m;
